using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DanaZhangCms.Domain.DbModels;
using DanaZhangCms.Domain.AutoMapper;
using System.Linq.Expressions;
using DanaZhangCms.Domain.ViewModel;
using DanaZhangCms.Helper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using DanaZhangCms.DbModels;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace DanaZhangCms.Areas.SysAdmin.Controllers
{
    [Area("SysAdmin")]
     [Authorize("Admin")]
    public class UserController : Controller
    {
         private readonly UserManager<User> _userManager;
        private MyContext dbContext;
       
        public UserController(MyContext _dbContext, UserManager<User> userManager)
        {
            this.dbContext = _dbContext;
             _userManager = userManager;
        }
        // GET: /<controller>/
        public IActionResult Index( int page = 1)
        {
           
            return View();
        }
   
    public async Task<JsonResult> IndexData(int page = 1, string key = "", int rows = 10)
        {
            Expression<Func<User, bool>> predicate = o => true;
            
            var query = dbContext.Users.Where(predicate);
            var count = query.Count();
            var data = query.OrderByDescending(o => o.Id).Skip((page - 1) * rows).Take(rows).Select(o=>new {o.UserName,o.CreateOn,o.Email,o.Id}).ToList();
            var pages = count % rows == 0 ? count / rows : count / rows + 1;
            return Json(new { records = count, page = page, total = pages, rows = data });
        }

        public IActionResult ChangePassword(int id)
        {
            var model = new ResetPasswordViewModel();
            model.Id=id;
            return View(model);
        }

       [HttpPost]
        public async Task<IActionResult> ChangePassword(ResetPasswordViewModel  model)
        {
              var user = await _userManager.FindByIdAsync(model.Id.ToString());
            if (user == null)
            {
                // Don't reveal that the user does not exist
                return Json(new {success=false,message="该用户为空"});
            }
            var code = await _userManager.GeneratePasswordResetTokenAsync(user);
            var result = await _userManager.ResetPasswordAsync(user,code,model.Password);
            if (result.Succeeded)
            {
                return Json(new {success=true,message="密码修改成功"});
            }
            else
            {
                 return Json(new {success=false,message="密码修改失败"});
            }
        
            return View();
        }

    }
}
